<html>
<head>
  <title><%= @operation_template.app %></title>
  <%= stylesheet_link_tag 'resources/css/ext-all' %>
  <%= stylesheet_link_tag 'CheckHeader' %>
  <%= stylesheet_link_tag 'msg' %>
  <%= javascript_include_tag "jquery.min" %>
  <%= javascript_include_tag "ext-all" %>
  <%= javascript_include_tag "ext-lang-zh_CN" %>
  <%= javascript_include_tag "CheckColumn" %>

  <%= csrf_meta_tag %>
</head>
<body>
<input type="hidden" id="app_id" value="<%= @operation_template.app.id %>"/>
<input type="hidden" id="app_name" value="<%= @operation_template.app.name %>"/>
<input type="hidden" id="operation_template_id" value="<%= @operation_template.id %>"/>

<input type="hidden" id="operation_template_name" value="<%= @operation_template.name %>"/>
<select id="operation_template_expression" style="display: none;">
  <% @operation_template.directive_templates do |directive_template, next_when_fail| %>
      <option value="<%= "#{directive_template.id}|#{next_when_fail}" %>"><%= directive_template.name %></option>
  <% end %>
</select>
<script type="text/javascript">
    /**
     * Created by JetBrains RubyMine.
     * User: liupengtao.pt
     * Date: 11-7-21
     * Time: 上午11:43
     * To change this template use File | Settings | File Templates.
     */
    Ext.QuickTips.init();
    Ext.onReady(function() {
        //请求获取指令组数据并解析
        var cmdGroupNodes = [];
        var csrf_token = $('meta[name="csrf-token"]').attr('content');
        var msgCt;//向其中加入显示消息的元素。
        function createBox(t, s) {
            return '<div class="msg"><h3>' + t + '</h3><p>' + s + '</p></div>';
        }

        //显示瞬时消息
        function msg(title, format) {
            if (!msgCt) {
                msgCt = Ext.core.DomHelper.insertFirst(document.body, {id:'msg-div'}, true);
            }
            var s = Ext.String.format.apply(String, Array.prototype.slice.call(arguments, 1));
            var m = Ext.core.DomHelper.append(msgCt, createBox(title, s), true);
            m.hide();
            m.slideIn('t').ghost("t", { delay: 1000, remove: true});
        }

        Ext.Ajax.request({
            url:"<%= directive_groups_path %>",
            callback:function(options, success, response) {
                var cmdGroups = Ext.decode(response.responseText);
                for (var i = 0; i < cmdGroups.length; i++) {
                    var cmdGroupNode = {};
                    var cmdGroup = cmdGroups[i];
                    cmdGroupNode.id = 'directive_group' + cmdGroup.id;
                    cmdGroupNode.text = cmdGroup.name;

                    //为指令组增加命令
                    var cmdDefs = cmdGroup.directive_templates;
                    if (cmdDefs.length == 0) {
                        cmdGroupNode.leaf = true;
                    } else {
                        var children = [];
                        for (var j = 0; j < cmdDefs.length; j++) {
                            var cmdDef = {};
                            cmdDef.id = 'directive_template' + cmdDefs[j].id;
                            cmdDef.text = cmdDefs[j].name;
                            cmdDef.leaf = true;

                            children[children.length] = cmdDef;
                        }
                        cmdGroupNode.children = children;
                    }
                    cmdGroupNodes[cmdGroupNodes.length] = cmdGroupNode;
                }
                var cmdGroupStore = Ext.create('Ext.data.TreeStore', {
                    root: {
                        text: '指令组列表',
                        expanded: true,
                        children:cmdGroupNodes
                    },
                    folderSort: true,
                    sorters: [
                        {
                            property: 'id',
                            direction: 'ASC'
                        }
                    ]
                });

                //系统所有的指令组树
                var cmdGroupTreePanel = Ext.create('Ext.tree.Panel', {
                    title: '当前系统所有命令',
                    region:'west',
                    store:cmdGroupStore,
                    collapsible:true,
                    width:200,
                    autoScroll:true,
                    viewConfig: {
                        plugins: {
                            ptype: 'treeviewdragdrop',
                            enableDrop:false
                        }
                    },
                    selModel:{
                        mode:'MULTI'
                    },
                    listeners:{
                        itemremove:function(parent, node) {
                            var nextSibling = node.nextSibling;
                            var newNode = node.createNode({
                                id:node.data.id,
                                text:node.data.text,
                                leaf:node.data.leaf
                            });
                            if (!node.isLeaf()) {
                                var childNodes = node.childNodes;
                                for (var i = 0,len = childNodes.length; i < len; i++) {
                                    newNode.appendChild({
                                        id:childNodes[i].data.id,
                                        text:childNodes[i].data.text,
                                        leaf:childNodes[i].data.leaf
                                    });
                                }
                            }
                            if (nextSibling) {
                                parent.insertBefore(newNode, nextSibling);
                            } else {
                                parent.appendChild(newNode);
                            }
                            if (node.isExpanded()) {
                                newNode.expand();
                            }
                            node.remove(true);
                        }
                    }
                });

                cmdGroupTreePanel.getSelectionModel().on('select', function(selModel, record) {
                    var nodes = selModel.getSelection();
                    if (record.isLeaf() && nodes.indexOf(record.parentNode) > -1) {
                        selModel.deselect(record);
                    }
                    if (!record.isLeaf() && !record.isRoot()) {
                        record.eachChild(function(child) {
                            selModel.deselect(child);
                        });
                    }
                    if (record.isRoot()) {
                        selModel.deselect(record);
                    }
                });

                function $(id) {
                    return document.getElementById(id);
                }

                function addDirectiveTemplateToOperationTemplate(parent, node, refNode) {
                    if (node) {
                        if (!node.isLeaf()) {
                            node.eachChild(function(child) {
                                var newChild = parent.createNode({
                                    _id:child.data.id,
                                    text:child.data.text,
                                    leaf:child.data.leaf,
                                    allowFailure:false
                                });
                                setTimeout(function() {
                                    parent.insertBefore(newChild, refNode);
                                }, 10);
                            });
                            setTimeout(function() {
                                node.removeAll();
                                node.remove();
                            }, 10);

                        } else if (node.data.allowFailure !== true) {
                            if (!node.data._id) {//当增加文件夹中的所有命令时需要注意的地方。
                                node.data._id = node.data.id;
                            }
                            node.data.allowFailure = false;
                        }
                    }
                }

                //增加命令到命令集
                function updateOperation() {
                    setTimeout(function() {
                        var expression = '';
                        //获取命令集表达式
                        cmdSetTreePanel.getRootNode().eachChild(function(child) {
                            var id = child.get('_id');
                            if (id.indexOf('directive_template') > -1) {
                                expression += id.substring('directive_template'.length) + (child.get('allowFailure') == true ? '|true' : '');
                            } else {
                                expression += id + (child.get('allowFailure') == true ? '|true' : '');
                            }
                            if (!child.isLast()) {
                                expression += ',';
                            }
                        });
                        if (!expression || expression.trim().length == 0) {
                            Ext.Msg.alert('提示', '操作模板中的指令模板不能为空');
                            return;
                        }
//                        alert(expression)
                        //更新命令集

                        Ext.Ajax.request({
                            url:"<%= apps_path %>/" + appId + '/operation_templates/' + cmdSetDefId,
                            method:'PUT',
                            params:{
                                authenticity_token:csrf_token,
                                'operation_template[name]':Ext.getCmp('cmdSetName').value,
                                'operation_template[expression]':expression
                            },
                            callback:function(options, success, response) {
                                var result = Ext.decode(response.responseText);
                                if (result.errors.expression) {
                                    Ext.Msg.alert('提示', result.errors.expression[0]);
                                    return;
                                }
                                msg('提示', '指令模板更新成功');
                            }
                        });
                    }, 500);
                }

                //获取操作模板的相关信息
                var appId = $('app_id').value;
                var appName = $('app_name').value;
                var cmdSetDefId = $('operation_template_id').value;
                var cmdSetDefName = $('operation_template_name').value;
                var cmdSetDefExpression = $('operation_template_expression').options;

                var cmdDefList = [];
                for (var i = 0, len = cmdSetDefExpression.length; i < len; i++) {
                    var option = cmdSetDefExpression[i];
                    var cmdDef = {};
                    var id = option.value.split('|');
                    if (id.length > 1 && id[1] == 'true') {
                        cmdDef.allowFailure = true;
                    } else {
                        cmdDef.allowFailure = false;
                    }
                    cmdDef._id = id[0];
                    cmdDef.text = option.text;
                    cmdDef.leaf = true
                    cmdDefList[cmdDefList.length] = cmdDef;
                }

                var cmdSetTreeStore = Ext.create('Ext.data.TreeStore', {
                    root: {
                        text: cmdSetDefName,
                        expanded: true,
                        children:cmdDefList
                    },
                    fields:['_id','text','allowFailure']
                });

                //操作模板树
                var cmdSetTreePanel = Ext.create('Ext.tree.Panel', {
                    title:'操作模板所有命令',
                    collapsible:true,
                    region:'center',
//                rootVisible:false,
                    autoScroll:true,
                    viewConfig: {
                        plugins: {
                            ptype: 'treeviewdragdrop'
                        }
                    },
                    store:cmdSetTreeStore,
                    listeners:{
                        //向操作模板中增加命令
                        iteminsert:function(parent, node, refNode) {
                            addDirectiveTemplateToOperationTemplate(parent, node, refNode);
                        },
                        itemappend:function(parent, node, index) {
                            addDirectiveTemplateToOperationTemplate(parent, node);
                        }
                    },
                    columns: [
                        {
                            xtype:'treecolumn',
                            text: '命令',
                            width:220,
                            dataIndex: 'text'
                        },
                        {
                            xtype:'treecheckcolumn',
                            text: '允许失败',
                            dataIndex: 'allowFailure',
                            listeners:{
                                checkchange:function(column, number, checked) {
                                    var root = this.up('treepanel').getRootNode();
                                    var node = root.getChildAt(number - 1);
                                    if (number == 0) {
                                        root.eachChild(function(child) {
                                            if (checked) {
                                                child.set('allowFailure', true);
                                            }
                                            else {
                                                child.set('allowFailure', false);
                                            }
                                            child.commit();
                                        });
                                        node = root;
                                    }
                                    node.commit();
//                                    updateOperation();
                                }
                            }
                        },
                        {
                            xtype: 'actioncolumn',
                            width: 20,
                            items: [
                                {
                                    icon   : "<%= root_path %>" + 'stylesheets/images/delete.gif',
                                    tooltip: '删除当前命令',
                                    handler: function(tree, rowIndex, colIndex) {
                                        var root = this.up('treepanel').getRootNode();
                                        if (rowIndex == 0) {
                                            root.removeAll();
                                        } else {
                                            var nodeToDeleted = root.getChildAt(rowIndex - 1);
                                            nodeToDeleted.remove();
                                        }

//                                        updateOperation();
                                    }
                                }
                            ]
                        }
                    ]
                });

                //显示操作模板树的信息
                var cmdSetPanel = Ext.create('Ext.panel.Panel', {
                    title:'操作模板',
                    region:'center',
                    collapsible:true,
                    layout:'border',
                    items:[
                        {
                            layout:'hbox',
                            frame:true,
                            region:'north',
                            items:[
                                {
                                    xtype:'textfield',
                                    fieldLabel:'操作模板名',
                                    id:'cmdSetName',
                                    value:cmdSetDefName,
                                    flex:3,
                                    enableKeyEvents:true,
                                    listeners:{
                                        keyup:function(text, e) {
                                            if (e.getKey() == Ext.EventObject.ENTER) {
//                                                updateOperation();
                                            }
                                        },
                                        blur:function() {
//                                            updateOperation();
                                        }
                                    }
                                },
                                {
                                    xtype:'button',
                                    flex:1,
                                    text:'保存',
                                    margin:'0 10 0 10',
                                    handler:function() {
                                        updateOperation();
                                    }
                                }
                            ]
                        },
                        cmdSetTreePanel
                    ]
                });

                var editOperationMainViewport = Ext.create('Ext.Viewport', {
                    renderTo:document.body,
                    layout: {
                        type: 'border',
                        padding: 5
                    },
                    defaults: {
                        split:true
                    },
                    items: [
                        cmdGroupTreePanel,
                        cmdSetPanel
                    ]
                });
            }
        });

    });

</script>
</body>
</html>